<?php
namespace app\admin\controller;

use think\Loader;
use think\Request;
use app\common\model\Product as ProductModel;
use app\admin\tool\Parser;
use app\common\model\Company as CompanyModel;

class Product extends  Base{


    /**
     * @return \think\response\View
     * @throws
     */
    public function index(){

        $this->data['title'] = '产品列表';
        $this->data['column'] = $this->column();
        $this->data['model'] = ProductModel::where([])->paginate(10);
        $this->data['parser'] = new Parser();

        return view('',$this->data);

    }


    public function add(){

        $this->data['factory_list'] = CompanyModel::where('type','2')->select();

        $this->data['title'] = '添加产品';

        return view('',$this->data);
    }

    public function edit(Request $request){
        $id = $request -> param('id');
        $this->data['title'] = '编辑产品';
        $this->data['model'] = ProductModel::get($id);
        $this->data['factory_list'] = CompanyModel::where('type','2')->select();

        return view('',$this->data);
    }


    public function handle(Request $request){
        $data = $request->post();
        $validate = Loader::validate("Product");
        if(!$validate->check($data)){
            $this->error($validate->getError());
        }

        $data['op_user'] = $this->admin->id;
        if(empty($data['id'])){
            $data['add_time'] = $data['update_time'] = time();
            $model = new ProductModel();
            $model->data($data);
            if($model->allowField(true)->save()){
                $this->success("新增成功");
            }
        }else{
            $data['update_time'] = time();
            $model = new ProductModel();
            if($model ->allowField(true)->save($data,['id'=>$data['id']])){
                $this->success("更新成功");
            }
        }

        $this->error("操作失败");
    }


    /**
     * 判断该产品 是否已经下单
     * 后期优化
     * @param Request $request
     * @throws
     */
    public function delete(Request $request){
        $id = $request->param('id');
        $model = ProductModel::get($id);
        if($model){
            $res = $model ->delete();
            if($res){
                $this->success("删除成功");
            }
        }

        $this->error("操作失败");
    }

    public function column(){
        return [
            'title'=>['name'=>'名称','fun'=>'text','options'=>''],
            'serial_number'=>['name'=>'产品编号','fun'=>'text','options'=>''],
            'market_price'=>['name'=>'市场价格','fun'=>'text','options'=>''],
            'sell_price'=>['name'=>'团购价格','fun'=>'text','options'=>''],
            'salary'=>['name'=>'佣金','fun'=>'text','options'=>''],
            'add_time'=>['name'=>'添加时间','fun'=>'datetime','options'=>['format'=>'Y-m-d']],
        ];
    }
}